package com.itheima.service.impl;

import com.itheima.dto.SlideBlockValidateCodeDTO;
import com.itheima.pojo.Member;
import com.itheima.service.MemberService;
import com.itheima.service.OrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mapper.OrderMapper;
import com.itheima.pojo.Order;
import com.itheima.service.OrderSettingService;
import com.itheima.support.SysConsts;
import com.itheima.utils.DateUtil;
import com.itheima.utils.RedisUtil;
import com.itheima.utils.SlideBlockValidateCodeUtils;
import com.itheima.utils.ValidateCodeUtils;
import com.tencentcloudapi.captcha.v20190722.models.DescribeCaptchaResultResponse;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.Date;
import java.util.Map;

@DubboService
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {
    @Autowired
    private MemberService memberService;
    @Autowired
    private OrderSettingService orderSettingService;

    @Transactional
    @Override
    public Order add(Map map) {
        String validateCode = (String) map.get("validateCode");
        if (ObjectUtils.isEmpty(validateCode)) {
            throw new RuntimeException("请输入验证码");
        }
        String telephone = (String) map.get("telephone");
        Integer rV = RedisUtil.get(SysConsts.ORDER_PRO_KEY + telephone);
        if (ObjectUtils.isEmpty(rV)) {
            throw new RuntimeException("验证码过期");
        }
        if (!rV.equals(Integer.parseInt(validateCode))) {
            throw new RuntimeException("验证码错误");
        }

        orderSettingService.updateReservations((String) map.get("orderDate"));
        Member member = memberService.isMemberRegisted((String) map.get("telephone"));
        if (!ObjectUtils.isEmpty(member)) {
            Integer i = baseMapper.hasSameOrderOrNot(member.getId(),(String) map.get("orderDate"));
            if (i > 0)
                throw new RuntimeException("已预约过此时段");
        }
        Member addMember = new Member();
        addMember.setId(member.getId());
        addMember.setName((String) map.get("name"));
        addMember.setTelephone((String) map.get("telephone"));
        addMember.setIdCard((String) map.get("idCard"));
        addMember.setCreateDate(new Date());
        addMember.setSex((String) map.get("sex"));
        memberService.saveOrUpdate(addMember);

        Order order = new Order();
        order.setSetmealId(Long.parseLong((String) map.get("setmealId")));
        order.setMemberId(member.getId());
        order.setOrderDate(DateUtil.parseDate((String) map.get("orderDate")));
        order.setOrderType(String.valueOf(map.get("orderType")));
        order.setStatus("1");
        this.save(order);

        return order;
    }

    @Override
    public Map findMSGById(Long id) {
        return baseMapper.findMSGById(id);
    }

    //根据订单ID查询支付状态
    @Override
    public String findStatusById(Long id) {
        return baseMapper.findStatusById(id);
    }

    @Override
    public String validate(String telephone, SlideBlockValidateCodeDTO slideBlockValidateCodeDTO) {
        DescribeCaptchaResultResponse validate = SlideBlockValidateCodeUtils.validate(slideBlockValidateCodeDTO);
        if (validate.getCaptchaCode()!=1){
            throw new RuntimeException("滑块验证失败");
        }
        Integer i = ValidateCodeUtils.generateValidateCode(4);
//        短信发送验证码
//        SMSUtils.sendMessage(telephone,i);
        RedisUtil.set(SysConsts.ORDER_PRO_KEY+telephone,i,60);
        return String.valueOf(i);
    }

    //支付成功,修改订单表的支付信息
    @Override
    public void updateState(long orderId) {

        baseMapper.updateState(orderId);
    }

    /**
     * 根据订单支付状态，处理订单信息
     * 0-未支付：直接删除该订单
     * 1-已支付：不理会
     *
     * @param orderId
     */
    @Override
    @Transactional      //开启事务
    public void dealOrderByPayStatus(long orderId) {
        String status = this.findStatusById(orderId);
        if ("0".equals(status)) {

            //根据订单ID，查询order_date
            String orderDate = baseMapper.queryOrderDateById(orderId);

            //未支付，或订单超时---删除该订单    订单表
            baseMapper.deleteOrderById(orderId);

            //同时修改对应的中间表信息  reservations -= 1
            int num = baseMapper.updateOrderSettingByDate(orderDate);

            if (num > 0) {
                System.out.println("------> 异常订单处理完成！！！");
            } else {
                throw new RuntimeException("=====sql执行时异常=====");
            }
        }
    }
}